// stores/storageStore.ts - Storage management store
import { create } from 'zustand';
import { storageService } from '../services/storage';
import type { StoragePoolDetail, StoragePoolSummary, StorageVolumeDetail, StorageVolumeSummary, CreateVolumeRequest, ApiResponse } from '../types/api';

interface StorageStore {
  // State
  storagePools: StoragePoolSummary[];
  currentPool: StoragePoolDetail | null;
  volumes: Record<string, StorageVolumeSummary[]>; // poolName -> volumes
  currentVolume: StorageVolumeDetail | null;
  loading: boolean;
  error: string | null;

  // Actions
  fetchStoragePools: (connection: string) => Promise<void>;
  getStoragePoolDetail: (connection: string, pool: string) => Promise<StoragePoolDetail>;
  createStoragePool: (connection: string, xmlConfig: string) => Promise<ApiResponse>;
  deleteStoragePool: (connection: string, pool: string) => Promise<ApiResponse>;
  startStoragePool: (connection: string, pool: string) => Promise<ApiResponse>;
  stopStoragePool: (connection: string, pool: string) => Promise<ApiResponse>;

  fetchStorageVolumes: (connection: string, pool: string) => Promise<void>;
  getStorageVolumeDetail: (connection: string, pool: string, volume: string) => Promise<StorageVolumeDetail>;
  createStorageVolume: (connection: string, pool: string, config: CreateVolumeRequest) => Promise<ApiResponse>;
  deleteStorageVolume: (connection: string, pool: string, volume: string) => Promise<ApiResponse>;

  clearError: () => void;
}

export const useStorageStore = create<StorageStore>((set, get) => ({
  // Initial state
  storagePools: [],
  currentPool: null,
  volumes: {},
  currentVolume: null,
  loading: false,
  error: null,

  // Actions
  fetchStoragePools: async (connection: string) => {
    set({ loading: true, error: null });
    try {
      const response = await storageService.listStoragePools(connection);
      set({
        storagePools: response.pools || response.items || [],
        loading: false
      });
    } catch (error) {
      set({
        error: 'Failed to fetch storage pools',
        loading: false
      });
    }
  },

  // 获取存储池详情
  getStoragePoolDetail: async (connection: string, pool: string) => {
    set({ loading: true, error: null });
    try {
      const poolDetail = await storageService.getStoragePoolDetail(connection, pool);
      set({
        currentPool: poolDetail,
        loading: false
      });
      return poolDetail;
    } catch (error) {
      set({
        error: 'Failed to fetch storage pool details',
        loading: false
      });
      throw error;
    }
  },

  // 创建存储池
  createStoragePool: async (connection: string, xmlConfig: string) => {
    set({ loading: true, error: null });
    try {
      const response = await storageService.createStoragePool(connection, xmlConfig);
      // 更新存储池列表
      await get().fetchStoragePools(connection);
      set({ loading: false });
      return response;
    } catch (error) {
      set({
        error: 'Failed to create storage pool',
        loading: false
      });
      throw error;
    }
  },

  // 删除存储池
  deleteStoragePool: async (connection: string, pool: string) => {
    set({ loading: true, error: null });
    try {
      const response = await storageService.deleteStoragePool(connection, pool);
      // 更新存储池列表
      await get().fetchStoragePools(connection);
      // 清除该存储池的卷数据
      set(state => {
        const volumes = { ...state.volumes };
        delete volumes[pool];
        return {
          volumes,
          loading: false
        };
      });
      return response;
    } catch (error) {
      set({
        error: 'Failed to delete storage pool',
        loading: false
      });
      throw error;
    }
  },

  // 启动存储池
  startStoragePool: async (connection: string, pool: string) => {
    try {
      const response = await storageService.startStoragePool(connection, pool);
      // 更新存储池列表
      await get().fetchStoragePools(connection);
      return response;
    } catch (error) {
      set({ error: 'Failed to start storage pool' });
      throw error;
    }
  },

  // 停止存储池
  stopStoragePool: async (connection: string, pool: string) => {
    try {
      const response = await storageService.stopStoragePool(connection, pool);
      // 更新存储池列表
      await get().fetchStoragePools(connection);
      return response;
    } catch (error) {
      set({ error: 'Failed to stop storage pool' });
      throw error;
    }
  },

  // 获取存储池卷列表
  fetchStorageVolumes: async (connection: string, pool: string) => {
    set({ loading: true, error: null });
    try {
      const response = await storageService.listStorageVolumes(connection, pool);
      set(state => ({
        volumes: {
          ...state.volumes,
          [pool]: response.volumes || response.items || []
        },
        loading: false
      }));
    } catch (error) {
      set({
        error: 'Failed to fetch storage volumes',
        loading: false
      });
    }
  },

  // 获取存储池卷详情
  getStorageVolumeDetail: async (connection: string, pool: string, volume: string) => {
    set({ loading: true, error: null });
    try {
      const volumeDetail = await storageService.getStorageVolumeDetail(connection, pool, volume);
      set({
        currentVolume: volumeDetail,
        loading: false
      });
      return volumeDetail;
    } catch (error) {
      set({
        error: 'Failed to fetch storage volume details',
        loading: false
      });
      throw error;
    }
  },

  // 创建存储池卷
  createStorageVolume: async (connection: string, pool: string, config: CreateVolumeRequest) => {
    set({ loading: true, error: null });
    try {
      const response = await storageService.createStorageVolume(connection, pool, config);
      // 更新存储池卷列表
      await get().fetchStorageVolumes(connection, pool);
      set({ loading: false });
      return response;
    } catch (error) {
      set({
        error: 'Failed to create storage volume',
        loading: false
      });
      throw error;
    }
  },

  // 删除存储池卷
  deleteStorageVolume: async (connection: string, pool: string, volume: string) => {
    set({ loading: true, error: null });
    try {
      const response = await storageService.deleteStorageVolume(connection, pool, volume);
      // 更新存储池卷列表
      await get().fetchStorageVolumes(connection, pool);
      set({ loading: false });
      return response;
    } catch (error) {
      set({
        error: 'Failed to delete storage volume',
        loading: false
      });
      throw error;
    }
  },

  // 清除错误
  clearError: () => set({ error: null }),
}));